package collection;

import banklogic.Account;
import banklogic.Mapable;
import banklogicimpl.AbstractAccount;


public class AccountsMap <V extends Account> implements Mapable<V>{

    private String [] accLabel;
    private String [] newAccLabel;
    private Object [] accSet;
    private Object [] newAccSet;
    private int size = 0;
    private int currentNumber = 0;

    public AccountsMap(int listSize) {

        accSet = new Object [listSize];
        accLabel =  new String[listSize];
        this.size = listSize;
        System.out.println("New set of accounts has been created. Size: " + listSize );
    }

    private void rebuild(int newSize){
        newAccSet = new Object[newSize];
        newAccLabel = new String[newSize];

        for (int i = 0; i < currentNumber; i++) {
            newAccSet[i] = accSet[i];
            newAccLabel[i] = accLabel[i];
        }
        accSet = newAccSet;
        accLabel = newAccLabel;
        size = newSize;
        System.out.println("Extending set...");
    }

    public void put(String key, V account){
        for (int i = 0; i < currentNumber; i++){
          if (accLabel[i].equals(key)) {
              remove(key);
          }
        }
        accSet[currentNumber] = account;
        accLabel[currentNumber] = key;
        currentNumber++;
        System.out.println("Just added account " + key);
        if (currentNumber > 0.6*size) rebuild(size * 2);
    }

    public V get (String key){
        for (int i = 0; i < currentNumber; i++){
            if (accLabel[i].equals(key)) return (V) accSet[i];
        }
        System.out.println("Account " + key + " not found");
        return null;
    }

    public boolean contains (Account acc){
        for (int i = 1; i < currentNumber; i++){
            if (accSet[i].equals(acc)) return true;
        }
        return false;
    }

    public boolean contains (String acc){
        for (int i = 1; i < currentNumber; i++){
            if (accLabel[i].equals(acc)) return true;
        }
        return false;
    }

    public void remove (String key){
        System.out.println("Removing account " + key + "...");
        for (int i = 0; i < currentNumber; i++){
           if (accLabel[i].equals(key)) {

               while (i < currentNumber-1)  {
               accSet[i] = accSet[i+1];
               accLabel[i] = accLabel[i+1];
               i++;
               }
               accSet[currentNumber] = null;
               accLabel[currentNumber] = null;
               System.out.println("Account " + key + " has been removed from the set");
               currentNumber--;
               return;
           }
        }
        System.out.println("Account not found");
    }
}
